package com.cskaoyan.service;


import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.module.bean.MarketCouponInfo;
import com.cskaoyan.module.bo.CouponCreateParamBo;
import com.cskaoyan.module.bo.CouponListParamsBo;
import com.cskaoyan.module.bo.CouponListUserParamBo;
import com.cskaoyan.module.ddp.bo.CouponMyListParamsBo;
import com.cskaoyan.module.ddp.vo.CouponListVo;
import com.cskaoyan.module.ddp.vo.CouponVo;
import com.cskaoyan.module.pojo.*;
import com.cskaoyan.module.vo.MarketCouponVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static java.time.LocalDate.now;

/**
 * PopularizeServiceImpl
 *
 * @param
 * @return
 * @2022/4/6
 **/
@Service
@Qualifier("popularizeServiceImpl")
public class PopularizeServiceImpl implements PopularizeService{
    @Autowired
    MarketCouponMapper marketCouponMapper;


    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Override
    public MarketCouponVo list(CouponListParamsBo params) {
        MarketCouponVo result=new MarketCouponVo();
//        分页语句

        PageHelper.startPage(params .getPage(),params.getLimit());
//        使用example

        MarketCouponExample example=new MarketCouponExample();
//        排序
        example.setOrderByClause(params.getSort()+ " "+params.getOrder());


        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
//        只有未删除状态的优惠卷才显示
        List<MarketCoupon> marketCoupons=null;
//        取出来前台可能传入的数据
//         ->如果传入数据不为空 则把这个数据放入到条件里
//         ->name 使用like
//         ->type 使用等于
//         ->status 使用等于
            String name = params.getName();
            Integer type = params.getType();
            Integer status = params.getStatus();
            if (name != null && !"".equals(name)) {
                criteria.andNameLike("%"+name+"%");
            }
            if (type != null && !"".equals(type)) {
                criteria.andTypeEqualTo(type);
            }
            if (status != null && !"".equals(status)) {
                criteria.andStatusEqualTo(status);
            }
//          条件查询 -> 获取list

            marketCoupons = marketCouponMapper.selectByExample(example);

//     使用分页插件 ->
        PageInfo<MarketCoupon> pageInfo=new PageInfo<>(marketCoupons);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        int pageNum = pageInfo.getPageNum();

//          遍历list 将所需要的成员变量封装到MarketCouponVo的list中
        List<MarketCouponVo.ListDTO> list=new ArrayList<>();
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCouponVo.ListDTO listDTO = new MarketCouponVo.ListDTO();
            listDTO.setId(marketCoupon.getId());
            listDTO.setName(marketCoupon.getName());
            listDTO.setDesc(marketCoupon.getDesc());
            listDTO.setTag(marketCoupon.getTag());
            listDTO.setTotal(marketCoupon.getTotal());
            listDTO.setDiscount(marketCoupon.getDiscount());
            listDTO.setMin(marketCoupon.getMin());
            listDTO.setLimit(marketCoupon.getLimit());
            listDTO.setStatus(marketCoupon.getStatus());
            listDTO.setGoodsType(marketCoupon.getGoodsType());
            listDTO.setGoodsValue(marketCoupon.getGoodsValue());
            listDTO.setTimeType(marketCoupon.getTimeType());
            listDTO.setDays(marketCoupon.getDays());
            listDTO.setUpdateTime(marketCoupon.getUpdateTime());
            listDTO.setAddTime(marketCoupon.getAddTime());
            listDTO.setDeleted(marketCoupon.getDeleted());
            list.add(listDTO);
        }
//        给MarketCouponVo的各个成员赋值
        result.setList(list);
//        result.setLimit(params.getLimit());
        //        page? pages?
        result.setPage(pageNum);
        result.setPages(pages);
        result.setTotal( total);
        result.setLimit(pageInfo.getSize());
        return result;
    }

    @Override
    public MarketCoupon create(CouponCreateParamBo params) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date currentTime= new java.util.Date();
        String timeNow= simpleDateFormat.format(currentTime);
        Date time= null;
        try {
            time = new Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeNow).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }

//        得到最大的id 作为优惠卷的号码
//        int code=marketCouponMapper.
//        获取id
//        获取code
//                用以返回！
        MarketCoupon marketCoupon = new MarketCoupon(null,
                params.getName(),
                params.getDesc(),
                params.getTag(),
                params.getTotal(),
                params.getDiscount(),
                params.getMin(),
                params.getLimit(),
                params.getType(),
                params.getStatus(),
                params.getGoodsType(),
                params.getGoodsValue(),
                null,
                params.getTimeType(),
                params.getDays(),
                params.getStartTime(),
                params.getEndTime()
                ,time,
                time,
                false
        );
//        优惠券兑换码code->  null
//        使用券截至时间endtime
//        创建时间adddate->当前
//        更新时间updatetime->当前
        int insert = marketCouponMapper.insertSelective(marketCoupon);
//        还要插入到goods???? 根据id插入商品名称和商品编号

        System.out.println("after insert marketCoupon的id = " + marketCoupon.getId());

        if (insert == 0) {
            System.out.println("marketCouponMapper insert = " + insert + ",出错了！");
            return null;
        } else {

            return marketCoupon;
        }
    }

    @Override
    public MarketCouponVo listUser(CouponListUserParamBo params) {
        MarketCouponVo result=new MarketCouponVo();
//        分页语句
        PageHelper.startPage(params.getPage(),params.getLimit());
        MarketCouponExample example=new MarketCouponExample();
        example.setOrderByClause(params.getSort()+ " "+params.getOrder());
        MarketCouponExample.Criteria criteria = example.createCriteria();
        if (params.getCouponId() != null|| !"".equals(params.getCouponId())) {
            criteria.andIdEqualTo(params.getCouponId());
        }
        if (params.getStatus() != -1 || !"".equals(params.getStatus())) {
            criteria.andStatusEqualTo(params.getStatus());
        }
//        TODO
        if (params.getUserId() != -1 || !"".equals(params.getUserId())) {
//            根据id查？

        }
        List<MarketCoupon> marketCoupons=marketCouponMapper.selectByExample(example);
        PageInfo<MarketCoupon> pageInfo=new PageInfo<>(marketCoupons);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        int pageNum = pageInfo.getPageNum();

        List<MarketCouponVo.ListDTO> list=new ArrayList<>();
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCouponVo.ListDTO listDTO = new MarketCouponVo.ListDTO();
            listDTO.setId(marketCoupon.getId());
            listDTO.setName(marketCoupon.getName());
            listDTO.setDesc(marketCoupon.getDesc());
            listDTO.setTag(marketCoupon.getTag());
            listDTO.setTotal(marketCoupon.getTotal());
            listDTO.setDiscount(marketCoupon.getDiscount());
            listDTO.setMin(marketCoupon.getMin());
            listDTO.setLimit(marketCoupon.getLimit());
            listDTO.setStatus(marketCoupon.getStatus());
            listDTO.setGoodsType(marketCoupon.getGoodsType());
            listDTO.setGoodsValue(marketCoupon.getGoodsValue());
            listDTO.setTimeType(marketCoupon.getTimeType());
            listDTO.setDays(marketCoupon.getDays());
            listDTO.setUpdateTime(marketCoupon.getUpdateTime());
            listDTO.setAddTime(marketCoupon.getAddTime());
            listDTO.setDeleted(marketCoupon.getDeleted());
            list.add(listDTO);
        }
        result.setList(list);
        result.setLimit(pageInfo.getSize());
        //        page? pages?
        result.setPage(pageNum);
        result.setPages(pages);
        result.setTotal(total);
        return result;
    }

    @Override
    @Transactional()
    public MarketCoupon update(MarketCoupon param) {
//        点击编辑 ->更新优惠卷的信息\
//        MarketCouponInfo result = new MarketCouponInfo();
        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        param.setUpdateTime(new Date());
        int update = marketCouponMapper.updateByPrimaryKeySelective(param);
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(param.getId());
        System.out.println("MarketCoupon update marketCoupon = " + marketCoupon);
        return marketCoupon;
    }

    @Override
    public int delete(MarketCoupon params) {
//       根据主键将delete的值置为true
        params.setDeleted(true);
        params.setUpdateTime(new Date());
        System.out.println("delete params = " + params);
        int update = marketCouponMapper.updateByPrimaryKeySelective(params);
        return update;
    }

    @Override
    public MarketCouponInfo read(Integer params) {
//        根据主键查优惠卷的数据
        MarketCoupon record = marketCouponMapper.selectByPrimaryKey(params);
        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
//        仅当删除状态为false才参与详情展示
//        example.setOrderByClause(params.);
        criteria.andIdEqualTo(params);
        criteria.andDeletedEqualTo(false);
//        获取当前时间 for 修改updateTime
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date currentTime= new java.util.Date();
        String timeNow= simpleDateFormat.format(currentTime);
//        Date time= null;
//        try {
//            time = new Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timeNow).getTime());
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        将查出来的记录的修改时间更新为最新的时间
        record.setUpdateTime(new Date());

//        TODO 之前空指针异常！主要是当前日期获取不到
//        根据条件更新
        marketCouponMapper.updateByExample(record,example);
//        获取marketCouponInfo 以返回给前台
        MarketCouponInfo marketCouponInfo = new MarketCouponInfo(
                record.getId(),
                record.getName(),
                record.getDesc(),
                record.getTag(),
                record.getTotal(),
                record.getDiscount(),
                record.getMin(),
                record.getLimit(),
                record.getType(),
                record.getStatus(),
                record.getGoodsType(),
                record.getGoodsValue(),
                record.getTimeType(),
                record.getDays(),
                record.getAddTime(),
                record.getAddTime(),
                record.getDeleted());
        return marketCouponInfo;
    }

    @Override
    public MarketCouponVo listLimit0(Integer limit) {
        MarketCouponVo result = new MarketCouponVo();

        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
//        仅当删除状态为false才参与详情展示
        criteria.andDeletedEqualTo(false);
        criteria.andLimitEqualTo(limit);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);
        List<MarketCouponVo.ListDTO> list=new ArrayList<>();
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCouponVo.ListDTO listDTO = new MarketCouponVo.ListDTO();
            listDTO.setId(marketCoupon.getId());
            listDTO.setName(marketCoupon.getName());
            listDTO.setDesc(marketCoupon.getDesc());
            listDTO.setTag(marketCoupon.getTag());
            listDTO.setTotal(marketCoupon.getTotal());
            listDTO.setDiscount(marketCoupon.getDiscount());
            listDTO.setMin(marketCoupon.getMin());
            listDTO.setLimit(marketCoupon.getLimit());
            listDTO.setStatus(marketCoupon.getStatus());
            listDTO.setGoodsType(marketCoupon.getGoodsType());
            listDTO.setGoodsValue(marketCoupon.getGoodsValue());
            listDTO.setTimeType(marketCoupon.getTimeType());
            listDTO.setDays(marketCoupon.getDays());
            listDTO.setUpdateTime(marketCoupon.getUpdateTime());
            listDTO.setAddTime(marketCoupon.getAddTime());
            listDTO.setDeleted(marketCoupon.getDeleted());
            list.add(listDTO);
        }
        PageInfo<MarketCoupon> pageInfo=new PageInfo<>(marketCoupons);
        int pages = pageInfo.getPages();
//        Integer total = ((Integer) pageInfo.getTotal());
        int pageNum = pageInfo.getPageNum();
        result.setList(list);
        result.setPage(pageNum);
        result.setPages(pages);
        result.setTotal( pageInfo.getTotal());
        result.setLimit(pageInfo.getSize());
        return result;
    }

    @Override
    public MarketCouponVo listAll() {
        MarketCouponVo result = new MarketCouponVo();
        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
//        仅当删除状态为false才参与详情展示
        criteria.andDeletedEqualTo(false);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);
        List<MarketCouponVo.ListDTO> list=new ArrayList<>();
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCouponVo.ListDTO listDTO = new MarketCouponVo.ListDTO();
            listDTO.setId(marketCoupon.getId());
            listDTO.setName(marketCoupon.getName());
            listDTO.setDesc(marketCoupon.getDesc());
            listDTO.setTag(marketCoupon.getTag());
            listDTO.setTotal(marketCoupon.getTotal());
            listDTO.setDiscount(marketCoupon.getDiscount());
            listDTO.setMin(marketCoupon.getMin());
            listDTO.setLimit(marketCoupon.getLimit());
            listDTO.setStatus(marketCoupon.getStatus());
            listDTO.setGoodsType(marketCoupon.getGoodsType());
            listDTO.setGoodsValue(marketCoupon.getGoodsValue());
            listDTO.setTimeType(marketCoupon.getTimeType());
            listDTO.setDays(marketCoupon.getDays());
            listDTO.setUpdateTime(marketCoupon.getUpdateTime());
            listDTO.setAddTime(marketCoupon.getAddTime());
            listDTO.setDeleted(marketCoupon.getDeleted());
            list.add(listDTO);
        }
        PageInfo<MarketCoupon> pageInfo=new PageInfo<>(marketCoupons);
        int pages = pageInfo.getPages();
//        Integer total = ((Integer) pageInfo.getTotal());
        int pageNum = pageInfo.getPageNum();
        result.setList(list);
        result.setPage(pageNum);
        result.setPages(pages);
        result.setTotal( pageInfo.getTotal());
        result.setLimit(pageInfo.getSize());
        return result;
    }
//查询优惠卷显示列表  status-0/1/2-对应不同的优惠卷情况未使用已使用已过期
    @Override
    public CouponVo mylist(CouponMyListParamsBo params) {
        CouponVo result=new CouponVo();
//      1.获取用户id

        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id=user.getId();
//      2.example
        MarketCouponUserExample example=new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(id);
        criteria.andStatusEqualTo(params.getStatus());
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example);
//         当删除状态为false->available未true
//        拿到couponId-> 遍历id -> 获取信息插入到表中 ->
        List<MarketCouponUser> usersList=new ArrayList<>();

        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            MarketCouponExample example1=new MarketCouponExample();
            MarketCouponExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andIdEqualTo(marketCouponUser.getCouponId());
            criteria1.andDeletedEqualTo(false);
            List<MarketCoupon> marketCouponsList = marketCouponMapper.selectByExample(example1);
            MarketCoupon marketCoupon = marketCouponsList.get(0);
            if (marketCoupon.getTimeType() == 0) {
                marketCouponUser.setStartTime(marketCoupon.getAddTime());
                marketCouponUser.setEndTime(addDate(marketCoupon.getAddTime(),marketCoupon.getDays()));

            } else if (marketCoupon.getTimeType() == 1) {
                marketCouponUser.setStartTime(marketCoupon.getStartTime());
                marketCouponUser.setEndTime(marketCoupon.getEndTime());
            }
            marketCouponUser.setUpdateTime(new Date());
            marketCouponUser.setAddTime(marketCoupon.getAddTime());
//            更新信息
            marketCouponUserMapper.updateByPrimaryKey(marketCouponUser);
            usersList.add(marketCouponUser);
        }

//      3.分页
        PageHelper.startPage(params.getPage(),params.getLimit());
//      4.返回分页信息
        PageInfo<MarketCouponUser> pageInfo=new PageInfo<>(marketCouponUsers);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        int page = pageInfo.getPageNum();
        int limit = params.getLimit();

        result.setLimit(limit);
        result.setPage(page);
        result.setPages(pages);
        result.setTotal(total);
//      5.list
        List<CouponVo.ListDTO> list=new ArrayList<>();
        for (MarketCouponUser marketCouponUser : usersList) {
            CouponVo.ListDTO listDTO = new CouponVo.ListDTO();
            listDTO.setId(marketCouponUser.getId());//当前这张表的id
            MarketCouponExample marketCouponExample=new MarketCouponExample();
            MarketCouponExample.Criteria exampleCriteria = marketCouponExample.createCriteria();
            exampleCriteria.andIdEqualTo(marketCouponUser.getCouponId());
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());


            listDTO.setCid(marketCoupon.getId());
            listDTO.setName(marketCoupon.getName());//优惠卷的name等
            listDTO.setDesc(marketCoupon.getDesc());
            listDTO.setTag(marketCoupon.getTag());
            listDTO.setMin(marketCoupon.getMin());
            listDTO.setDiscount(marketCoupon.getDiscount());
//            startTime和endTime 来自于user-coupon表！
            listDTO.setStartTime(marketCouponUser.getStartTime());
            listDTO.setEndTime(marketCouponUser.getEndTime());
            listDTO.setDeleted(marketCoupon.getDeleted());
            Date date = new Date();
            if (marketCoupon.getEndTime() != null) {
//             有指定时间就判断时间
                listDTO.setAvailable(marketCoupon.getEndTime().getTime() > date.getTime());
                System.out.println("mylist :marketCoupon.getEndTime().getTime() > date.getTime() = " + (marketCoupon.getEndTime().getTime() > date.getTime()));
            } else {
//                如果没有指定时间就设置为true即可
                listDTO.setAvailable(true);
            }
            //listDTO.setAvailable(marketCoupon.getDeleted());
            list.add(listDTO);
        }
        result.setList(list);
        return result;
    }
    public static Date addDate(Date date, long day)  {
        long time=0; // 得到指定日期的毫秒数
        try {
            time = date.getTime();
            day = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
            time += day; // 相加得到新的毫秒数
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Date(time); // 将毫秒数转换成日期
    }
    @Override
    public MarketCouponUser  receive(Integer couponId) {
//        领取优惠卷
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id=user.getId();

        MarketCoupon  result= new MarketCoupon ();
        //      2.example
        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(couponId);
        List<MarketCoupon> marketCouponsList = marketCouponMapper.selectByExample(example);
        result = marketCouponsList.get(0);
//        插入到coupon_user表中

//        如果查表得到已领取 就提示已领取！
        MarketCouponUserExample example2=new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andDeletedEqualTo(false);
        criteria2.andUserIdEqualTo(id);
        criteria2.andStatusEqualTo(0);
        criteria2.andCouponIdEqualTo(result.getId());

        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example2);
        if (marketCouponUsers.size() != 0) {
            return null;
        }
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setUserId(id);
        marketCouponUser.setStatus(result.getStatus());
        marketCouponUser.setAddTime(new Date());
        marketCouponUser.setUpdateTime(new Date());
        if (result.getTimeType() == 0) {
            marketCouponUser.setStartTime(result.getAddTime());
            marketCouponUser.setEndTime(addDate(result.getAddTime(),result.getDays()));

        } else if (result.getTimeType() == 1) {
            marketCouponUser.setStartTime(result.getStartTime());
            marketCouponUser.setEndTime(result.getEndTime());
        }
        marketCouponUser.setDeleted(false);
        marketCouponUser.setCouponId(result.getId());
        marketCouponUser.setOrderId(null);

        marketCouponUserMapper.insertSelective(marketCouponUser);
        return marketCouponUser;

    }

    @Override
    public MarketCoupon exchange(String code) {
        MarketCoupon result= new MarketCoupon();
//      1.获取用户id

        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id=user.getId();
//      2.example
        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andStatusEqualTo(0);
        criteria.andCodeEqualTo(code);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);


//        优惠卷不存在！
        if (marketCoupons.size() == 0) {
            return null;
        }
        MarketCoupon marketCoupon = marketCoupons.get(0);
//        优惠卷存在！
//        查一下是否已经领取！
        //        如果查表得到已领取(什么状态都行！) 就提示已领取！
        MarketCouponUserExample example2=new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andDeletedEqualTo(false);
        criteria2.andUserIdEqualTo(id);
        criteria2.andCouponIdEqualTo(marketCoupon.getId());

        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example2);
        if (marketCouponUsers.size() !=0) {
            return null;
        }
//存在这个卷 而且未领取就领取！
//        领取 marketCoupon这张优惠卷！
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setUserId(id);
        marketCouponUser.setStatus(marketCoupon.getStatus());
        marketCouponUser.setAddTime(new Date());
        marketCouponUser.setUpdateTime(new Date());
        if (marketCoupon.getTimeType() == 0) {
            marketCouponUser.setStartTime(marketCoupon.getAddTime());
            marketCouponUser.setEndTime(addDate(marketCoupon.getAddTime(),marketCoupon.getDays()));

        } else if (marketCoupon.getTimeType() == 1) {
            marketCouponUser.setStartTime(marketCoupon.getStartTime());
            marketCouponUser.setEndTime(marketCoupon.getEndTime());
        }
        marketCouponUser.setDeleted(false);
        marketCouponUser.setCouponId(marketCoupon.getId());
        marketCouponUser.setOrderId(null);
        marketCouponUserMapper.insertSelective(marketCouponUser);
        result=marketCoupon;
        return result;
    }

    @Override
    public CouponVo selectlist(Integer cartId, Integer grouponRulesId) {
        CouponVo result=new CouponVo();
//      1.获取用户id

        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id=user.getId();
//      2.example
        MarketCouponUserExample example=new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(id);
//       根据userId查询到已领取的优惠卷
//        查了就要更新一下- 并用新的集合保存一下
//
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example);

//        拿到couponId-> 遍历id -> 获取信息插入到表中 ->
        List<MarketCouponUser> usersList=new ArrayList<>();

        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            MarketCouponExample example1=new MarketCouponExample();
            MarketCouponExample.Criteria criteria1 = example1.createCriteria();
//            根据每个未删除状态下的优惠卷的id查询出优惠卷的信息并封装以返回！
            criteria1.andIdEqualTo(marketCouponUser.getCouponId());
            criteria1.andDeletedEqualTo(false);
            List<MarketCoupon> marketCouponsList = marketCouponMapper.selectByExample(example1);
            MarketCoupon marketCoupon = marketCouponsList.get(0);
            if (marketCoupon.getTimeType() == 0) {
//                days类型！
                marketCouponUser.setStartTime(marketCoupon.getAddTime());
                marketCouponUser.setEndTime(addDate(marketCoupon.getAddTime(),marketCoupon.getDays()));

            } else if (marketCoupon.getTimeType() == 1) {
//                绝对时间类型！
                marketCouponUser.setStartTime(marketCoupon.getStartTime());
                marketCouponUser.setEndTime(marketCoupon.getEndTime());
            }
            marketCouponUser.setUpdateTime(new Date());
            marketCouponUser.setAddTime(marketCoupon.getAddTime());
//            更新信息
            marketCouponUserMapper.updateByPrimaryKey(marketCouponUser);
            usersList.add(marketCouponUser);
        }

//      3.分页

//      4.返回分页信息
        PageInfo<MarketCouponUser> pageInfo=new PageInfo<>(usersList);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();
        int page = pageInfo.getPageNum();
        int limit = pageInfo.getSize();

        result.setLimit(limit);
        result.setPage(page);
        result.setPages(pages);
        result.setTotal(total);
//      5.list
        List<CouponVo.ListDTO> list=new ArrayList<>();
        for (MarketCouponUser marketCouponUser : usersList) {
            CouponVo.ListDTO listDTO = new CouponVo.ListDTO();
            listDTO.setId(marketCouponUser.getId());//当前这张表的id
            MarketCouponExample marketCouponExample=new MarketCouponExample();
            MarketCouponExample.Criteria exampleCriteria = marketCouponExample.createCriteria();
            exampleCriteria.andIdEqualTo(marketCouponUser.getCouponId());
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCouponUser.getCouponId());


            listDTO.setCid(marketCoupon.getId());
            listDTO.setName(marketCoupon.getName());//优惠卷的name等
            listDTO.setDesc(marketCoupon.getDesc());
            listDTO.setTag(marketCoupon.getTag());
            listDTO.setMin(marketCoupon.getMin());
            listDTO.setDiscount(marketCoupon.getDiscount());
//            startTime和endTime 来自于user-coupon表！
            listDTO.setStartTime(marketCouponUser.getStartTime());
            listDTO.setEndTime(marketCouponUser.getEndTime());
            listDTO.setDeleted(marketCoupon.getDeleted());
            //Date date = new Date();
            Date date = new Date(System.currentTimeMillis());
            //listDTO.setAvailable((marketCouponUser.getEndTime().getTime() > date.getTime())&&( marketCouponUser.getStartTime().getTime()<date.getTime()));

            long time = marketCouponUser.getEndTime().getTime();
            long time1 = date.getTime();
            listDTO.setAvailable((time > time1)&&( marketCouponUser.getStartTime().getTime() <time1));


            System.out.println("优惠卷设置sAvailable : = " + (marketCouponUser.getEndTime().getTime() > date.getTime()));
            list.add(listDTO);
        }
        System.out.println("result的内层值！list = " + list);
        result.setList(list);
        System.out.println("result 的值！result= " + result);
        return result;

    }
    @Override
    //    显示可领取的优惠卷->全商品可领取的！
    public CouponListVo listAllCoupons(CouponMyListParamsBo params) {
        CouponListVo result = new CouponListVo();
        MarketCouponExample example=new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
//        仅当删除状态为false才参与详情展示
        criteria.andDeletedEqualTo(false);
        criteria.andGoodsTypeEqualTo(0);
        criteria.andStatusEqualTo(0);
        PageHelper.startPage(params.getPage(),params.getLimit());
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);


        PageInfo<MarketCoupon> pageInfo=new PageInfo<>(marketCoupons);
        int pages = pageInfo.getPages();
//        Integer total = ((Integer) pageInfo.getTotal());
        int pageNum = pageInfo.getPageNum();
        result.setList(marketCoupons);
        result.setPage(pageNum);
        result.setPages(pages);
        result.setTotal((int) pageInfo.getTotal());
        result.setLimit(pageInfo.getSize());
        return result;
    }

}
